﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Windows.Forms;
using AutomationFramework;
using System.Windows.Automation.Provider;

namespace TreeControl
{
    public partial class Tree : UserControl
    {
        private List<TreeItem> myItems = new List<TreeItem>();

        public Tree()
        {
            InitializeComponent();
        }

        public TreeItem[] Items
        {
            get
            {
                return myItems.ToArray();
            }
        }

        public TreeItem AddItem(string id, string name)
        {
            int locationY = 0;
            foreach (TreeItem item in myItems)
            {
                locationY += item.BoundingRectangle.Height;
            }
            TreeItem tempItem = new TreeItem(id, name, this.Width, locationY);
            myItems.Add(tempItem);
            return tempItem;
        }

        public TreeItem ValueFromPoint(Point clientPoint)
        {
            TreeItem item = GetClickedItem(clientPoint);

            return item;
        }

        private TreeItem GetClickedItem(Point location)
        {
            TreeItem clickedItem = null;

            foreach (TreeItem item in myItems)
            {
                if (item.BoundingRectangle.Contains(location))
                {
                    clickedItem = item;
                    break;
                }
            }
            return clickedItem;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            DrawItem(e.Graphics, myItems);
            base.OnPaint(e);
        }

        private void DrawItem(Graphics graphics, IList<TreeItem> items)
        {
            foreach (TreeItem item in items)
            {
                item.Draw(graphics);
                if (item.Items.Length > 0)
                {
                    DrawItem(graphics, item.Items);
                }
            }
        }

        #region Automation Related
        protected override void WndProc(ref Message m)
        {
            // Handle WM_GETOBJECT
            if (m.Msg == 0x3D /* WM_GETOBJECT */)
            {
                m.Result = AutomationInteropProvider.ReturnRawElementProvider(
                    m.HWnd, m.WParam, m.LParam, this.Provider);
            }
            else
            {
                base.WndProc(ref m);
            }
        }

        private ControlProvider provider;
        private IRawElementProviderSimple Provider
        {
            get
            {
                if (this.provider == null)
                {
                    this.provider = new ControlProvider(this, ConfigFiles.TreeControlApiMapping);
                }
                return this.provider;
            }
        }
        #endregion
    }
}
